<script setup>
import { Delete, Download, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {ref} from 'vue'
import { onMounted } from 'vue'; 
import{getUserList,addUser,updateUser,deleteUser,batchDeleteUser} from '../../api/user.js';
import { ElMessage,ElMessageBox } from 'element-plus';

onMounted(()=>{
  getData()
  
})

const tableData = ref([])

const getData = () => {
  getUserList({
    currentPage: pagination.value.currentPage,
    pageSize:    pagination.value.pageSize
  })
  .then(res => {
    tableData.value = res.data.list
    pagination.value.total = res.data.total
  })
  .catch(error => {
    alert(error.message)
  })
}
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1   
  getData()
}

const handleCurrentChange=(val) => {
  pagination.value.currentPage=val
  getData()
}

const pagination = ref({
  currentPage: 1,
  pageSize: 3,
  total: 0,
})

const formRef = ref(null)

const title = ref('')

const dialogFormVisible = ref(false)

const handleAddModel = () =>{
  dialogFormVisible.value = true
  title.value = "新增用户"
}

const handleEdit=(row)=>{ 
  dialogFormVisible.value = true;
  title.value = "编辑用户"
  
  formData.value = row
}

const handleDelete=(id)=>{
  ElMessageBox.confirm(
    '此操作将删除该用户, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    
    })
    .then(()=>{
      deleteUser(id).then((res)=>{ 
        ElMessage.success(res.message)
        getData()
      })
    })
    .catch((error)=>{
      ElMessage({
        type: 'info',
        message: '取消删除'
        })
      })
}

const formData = ref({
  id:'',
  username:'',
  password:'',
  phone:'',
  photo:'',
  dept:'',
  status: '',
})

const rules = {
    username: [
      { 
        required: true,
        message: '请输入用户名', 
        trigger: 'blur'
    }
],
    password: [
      { 
        required: true,
        message: '请输入密码', 
        trigger: 'blur' 
    },
      { 
        min: 6,
        max: 15, 
        message: '长度在 6 到 15 个字符', 
    }
],
    dept:[
        {
            required: true,
            message: '请输入所属部门', 
            trigger: 'blur' 

    }
    ],
    phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ]
}

const cancel = ()=>{
  dialogFormVisible.value = false
  reset()
}

const reset = ()=>{
  
  formData.value = {
    id:'',
    username:'',
    password:'',
    phone:'',
    photo:'',
    dept:'',
    status:''
  }
}

const submitForm = async (row) => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (formData.value.id) {
                
                updateUser(formData.value).then(res => {
                    if (res.code == 200) {
                        ElMessage.success(res.message)
                        cancel()
                        reset()
                        getData()
                    } else {
                        ElMessage.error(res.message)
                    }
                }).catch(error => {
                    ElMessage.error(error.message)
                })
            } else {
                
                addUser(formData.value).then(res => {
                    if (res.code == 200) {
                        ElMessage.success(res.message)
                        
                        cancel()
                        
                        getData()
                        
                        reset()
                    } else {
                        ElMessage.error(res.message)
                    }
                }).catch((error) => {
                    ElMessage.error(error.message)
                })
            }
        }
    })
}

const handleSuccess = (res) => {
  console.log(res)
  formData.value.photo=res.data

}



 const handleExportExcel=()=>{
     window.open("http://localhost:8080/api/export")
  }

const importExcelSuccess=(res)=>{
  if(res.code==200){
    ElMessage.success(res.message)
  }else{
    ElMessage.error(res.message)
  }
  getData()
}


const selectedRows = ref([])
const multipleTableRef = ref()


const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `此操作将永久删除选中的 ${selectedRows.value.length} 个用户, 是否继续?`, 
    '提示', 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    batchDeleteUser(ids).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.message)
        getData()
        
        multipleTableRef.value.clearSelection()
      } else {
        ElMessage.error(res.message)
      }
    }).catch((error) => {
      ElMessage.error(error.message)
    })
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

</script>
<template>
  <div class="user-box">
    <el-row>
      <el-col>
        <div class="grid-content ep-bg-purple">
          <el-form :inline="true">
            <el-form-item class="input-item">
              <el-input placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="value" class="m-2" placeholder="请选择用户状态"  style="width: 200px">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
                <el-option />
              </el-select>
            </el-form-item>
            <el-button type="primary" :icon="Search" class="btn">搜索</el-button>
            <el-button plain type="primary" :icon="Refresh" class="btn">重置</el-button>
          </el-form>
          <div class="btn-group">
            <el-button type="primary" :icon="Plus" @click="handleAddModel">添加</el-button>
            <el-upload :action="'http://localhost:8080/api/import'" :on-success="importExcelSuccess" :show-file-list="false" class="upload-excel">
              <el-button type="success" :icon="Download">导入</el-button>
            </el-upload>
            <el-button type="info" :icon="Upload" @click="handleExportExcel">导出</el-button>
            <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <el-row>
        <div class="grid-content ep-bg-purple-dark">
          <el-table ref="multipleTableRef" :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30" />
            <el-table-column label="序号" width="70" type="index" />
            <el-table-column property="username" width="100" label="用户名称" />
            <el-table-column property="phone" width="120" label="电话号码" />
            <el-table-column property="dept" label="所属部门" />
            <el-table-column property="photo" label="头像" >
              <template #default="scope">
                <div class="deom-image__previw">
                  <el-image style="width: 40px; height: 40px;" :src="'http://localhost:8080' + scope.row.photo"
                  :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="srcList"
                  :initial-index="4" fit="cover"/>
                </div>        
              </template>
            </el-table-column>
            <el-table-column property="status" label="状态" >
              <template #default="scope">
                <el-switch
            v-model="scope.row.status"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            inline-prompt
            :active-value=1
            :inactive-value=0
          ></el-switch>
              </template>
            </el-table-column>
            <el-table-column property="createTime" label="创建时间" />
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button type="primary" @click="handleEdit(scope.row)" >编辑</el-button>   
                <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
              </template>
              </el-table-column>
          </el-table>
          <div class="pagination">
          <el-config-provider :locale="zhCn">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total=pagination.total @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
            </el-config-provider>
        </div>
        </div>
    </el-row>
    
    <el-dialog v-model="dialogFormVisible" title="添加用户" width="600">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" size="large" />
      </el-form-item>
       <el-form-item label="手机号码" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="所属部门" prop="dept">
        <el-input v-model="formData.dept" placeholder="请输入所属部门" />
      </el-form-item>
       <el-form-item label="登录密码" prop="password">
        <el-input v-model="formData.password" type="password" show-password="true" placeholder="请输入登录密码" />
      </el-form-item>
       <el-form-item label="状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态" style="margin-left: 10px;">
        <el-switch v-model="formData.status" :active-value=1
      :inactive-value=0 inline-prompt active-text="启用" inactive-text="禁用"
  />
      </el-form-item>
       <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload v-model:file-list="fileList"
        action="http://localhost:8080/api/upload" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess">
        <el-icon>
          <Plus />
        </el-icon>
  </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="cancel" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>
<style scoped>
.grid-content {
  width: 100%;
  background-color: #fff;
  margin: 5px;
   padding-bottom: 10px;
}

.input-item {
  width: 200px;
  padding: 20px;
}

.el-form {
  text-align: left;
}

.el-select {
  margin-left: -30px;
}

.el-button:focus {
  outline: none;
}

.btn{
  margin-top: -20px;
}

.btn-group {
  text-align: left;
  display: flex;
  margin-top: -20px;
  margin-left: 20px;
}

:deep() .el-dialog__header{
  text-align: left;
}

:deep() .el-button:focus {
  border: none;
}
.upload-excel{ 
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
  
}
</style>